package cn.player.download.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.entity.FileEntity;

import cn.player.utils.AESUtil;
import cn.player.utils.Constant;
import cntv.player.core.util.LogUtil;
import android.util.Log;

public class DecryptFileEntity extends FileEntity {

	public DecryptFileEntity(File file, String contentType) {
		super(file, contentType);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		// TODO Auto-generated method stub
//		super.writeTo(outstream);
		Log.d("DD", "-----------  dd file entity ----------");
		
		// 解密过程 
		InputStream instream = null;
		try {
			instream = new FileInputStream(this.file);
			int OUTPUT_BUFFER_SIZE = 1024;
			byte[] buffer = new byte[OUTPUT_BUFFER_SIZE]; 
			int len = 0; 
			int length = 0;
			while ((len = instream.read(buffer)) != -1) {
				length = length + len;
				if (length <= Constant.KB_BYTE
						&& file.getPath().endsWith(Constant.SUFFIX_VIDEO)) {// 总大小小于指定大小时加密处理
					LogUtil.i("zl", "length = " + length + ",len = " + len);
					buffer = AESUtil.decrypt(buffer, AESUtil.PSD);
					// for (int i = 0; i < buffer.length; i++) {
					// buffer[i] = (byte) (buffer[i] ^ 100); // 字节和100 异或 解密
					// }
					// buffer = DESUtil.decrypt(buffer, DESUtil.PSD);//Des解密有问题...?
				}
				outstream.write(buffer, 0, len);
			}
			outstream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally { 
			if (instream != null) {
				instream.close();
				instream = null;
			}
		}
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public static void readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
	}
}
